'use strict';

angular.module('hackathonApp')
  .controller('ProvidersCtrl', function ($scope, ProviderService) {
	  $scope.providers = [];

      $scope.filterText = "";
      //$scope.filterZipCode = "";
  	  //$scope.filterDistance= 10;
	 

      //paging
      $scope.totalServerItems = 0;
      $scope.pagingOptions = {
          pageSizes: [5, 10, 15,20],
          pageSize: 12,
          currentPage: 1
      };

      //sort
      $scope.sortInfo = {
          fields: ['custom_score'],
          directions: ['DESC']
      };

      $scope.looper = function (count) {
        var i = 0,
            count,
            build = new Array();

        for(i; i < count; i++){
          build[i] = i;
        }
        return build;
      }

      $scope.refresh = function () {
          setTimeout(function () {
              var sb = [];
              for (var i = 0; i < $scope.sortInfo.fields.length; i++) {
                  sb.push($scope.sortInfo.fields[i]+" "+$scope.sortInfo.directions[i]);
              }

              var params = {
                  searchText: $scope.filterText.toLowerCase(),
                  searchZipCode: $scope.filterZipCode,
                  searchDistance: $scope.filterDistance,
                  pageNumber: $scope.pagingOptions.currentPage,
                  pageSize: $scope.pagingOptions.pageSize,
                  sortInfo: sb.join(",")
              };

              ProviderService.query(params,function(response) {
                  $scope.totalServerItems = response.totalItems;
		              $scope.providers = response.items;
                  console.log($scope.providers);
              });
          }, 100);
      };
	  
	$scope.refresh();
	  

      /*//watches
      $scope.$watch('pagingOptions', function (newVal, oldVal) {
          if (newVal !== oldVal) {
              $scope.refresh();
          }
      }, true);

      $scope.$watch('filterOptions', function (newVal, oldVal) {
          if (((newVal.filterText !== oldVal.filterText) && newVal.filterText.length > 2) || ((newVal.filterZipCode != oldVal.filterZipCode) && newVal.filterZipCode.length > 4)) {
              $scope.refresh();
          }
      }, true);

      $scope.$watch('sortInfo', function (newVal, oldVal) {
          if (newVal !== oldVal) {
              $scope.refresh();
          }
      }, true);*/
	  
	  $scope.search = function() {
		  $scope.refresh();
	  }
  });

angular.module('hackathonApp')
  .controller('ProvidersFormCtrl', function ($scope, $routeParams, ProviderService) {
      if($routeParams.id) {
    	  ProviderService.get({id: $routeParams.id}, function(response) {
                    $scope.provider = response;
    		$scope.DNB.Api.get('V4.0/organizations?TerritoryName-1=' + response.state + '&CountryISOAlpha2Code-1=US&KeywordText=' + response.provname + '&SearchModeDescription=Advanced&findcompany=true').done(function(response) {
    			if (typeof(response.FindCompanyResponse) != 'undefined' && response.FindCompanyResponse.FindCompanyResponseDetail.CandidateReturnedQuantity) {
    			    $scope.companies = response.FindCompanyResponse.FindCompanyResponseDetail.FindCandidate;
    			    $scope.provider.duns = $scope.companies[0].DUNSNumber;
    				
    				// My change
    				$scope.getCompanyInfo();
    			    
    				$scope.$apply();
    			}
     		});
      });
    }

	  // Related api calls
	  $scope.getCompanyInfo  = function() {
		$scope.DNB.Api.get('/V3.0/organizations/'+ $scope.provider.duns +'/products/PBPR_STD').done(function (response){
			$scope.provider_assessment = response.OrderProductResponse.OrderProductResponseDetail.Product.Organization;
			$scope.$apply();
         });
				console.log($scope.provider.address);
		var fraud_url = 'V4.0/organizations?TerritoryName='+encodeURIComponent($scope.provider.state)+'&CountryISOAlpha2Code=US&StreetAddressLine-1='+encodeURIComponent($scope.provider.address)+'&PrimaryTownName='+$scope.provider.city+'&SubjectName='+encodeURIComponent($scope.provider.provname)+'&fraudscore=true';
		$scope.DNB.Api.get(fraud_url).done(function (response) {
			$scope.fraud_score = response.GetFraudScoreResponse.GetFraudScoreResponseDetail.FraudRiskScore.AddressReliabilityText;
			$scope.fraud_score_desc = response.GetFraudScoreResponse.GetFraudScoreResponseDetail.FraudRiskScore.ClassScoreDescription;
			$scope.$apply();
		});
		$scope.DNB.Api.get('/V3.0/organizations/'+ $scope.provider.duns +'/products/TLP').done(function  (response){
			$scope.provider_tlp = response.OrderProductResponse.OrderProductResponseDetail.Product.Organization.Assessment.TotalLossPredictorScore;
			//			console.log($scope.provider_tlp);
			$scope.$apply();
		});
		$scope.DNB.Api.get('/V3.0/organizations/'+ $scope.provider.duns +'/products/VIAB_RAT').done(function  (response){

		    console.log(response.OrderProductResponse.OrderProductResponseDetail.Product.Organization.Assessment);

		    $scope.viability_rating = response.OrderProductResponse.OrderProductResponseDetail.Product.Organization.Assessment.DNBViabilityRating.ViabilityScore.ClassScore;
		    
		    console.log($scope.viability_rating);
		    $scope.$apply();
		});
		}
});
